use sqlx::postgres::PgPool;
use axum::response::{IntoResponse};
use axum::http::StatusCode;
use axum::extract::{Extension};
use crate::error::user_error::user_error_map;
use crate::model::user_model;
use crate::types::user_types::*;
use crate::types::base_types::*;
use crate::error::base_error::Json;
use axum_client_ip::ClientIp;
use crate::handler::base::{new_token,create_the_time,encode_password}; 

/// 新增用户
pub async fn add_user(
    Json(req): Json<CreateUserReq>,
    ClientIp(_ip): ClientIp,
    Extension(pool): Extension<PgPool>,
) -> impl IntoResponse {
    match new_token(&req.phone, &req.password).await {
        Ok(token) => {
            let time = create_the_time().await;
            let hash_password = encode_password(&req.password).await;
            match user_model::create_user(&pool, &req.phone, &hash_password, &token, &time, &req.conuntry).await {
                Ok(result) => {
                    (StatusCode::OK, Json(BaseGetData::ok(result)))
                }
                Err(e) => {
                    (StatusCode::BAD_REQUEST, Json(BaseGetData::err(user_error_map(e).await,false)))
                }
            }
        }
        Err(err) => {
            (StatusCode::BAD_REQUEST, Json(BaseGetData::err(err.to_string(),false)))
        }
    }
}